<script type="text/javascript">
String.prototype.trim=function(){
    return this.replace(/(^\s*)|(\s*$)/g, "");
}
function myKeypress(event){return (/[\d]/.test(String.fromCharCode(event.keyCode||event.charCode)));}
function myFocus(){
	var v = parseInt($.formatNumber(this.value, "##0.00"), 10);
	if(isNaN(v)){
		v = 0;
	}
	this.value = v;
	$(this).data("before", v);
}

function myPaste(){
	return false;
}
function myChange(){
	var v = parseInt(this.value, 10);
	if(isNaN(v)){
		v = 0;
	}
	this.value = v;
}


function isDate(str){ 
	var reg = /\d{4}-\d{2}-\d{2}/
	if (reg.test(str)) 
		return true;
	return false;
}

function initSearchProduct(){
	$("#searchProductId").val('');
	$("#searchProductNumber").val('')
	$("#searchProductName").html('');
	$("#searchProductStandard").html('')
	$("#searchProductPrice").html('')
}

$(document).ready(function() {
    //industry list auto complete
	$("#industryInput").autocomplete({
	      minLength: 0
        , source: function(request, response) {
                $.ajax({
                   url: "${createLink(controller:'salesOrderAjax', action: 'industryList')}",
                   data: { term: request.term },
                   dataType: "json",
                   type: "POST",
                   success: function( data ) {
                       response( $.map( data, function( item ) {
                           return {
                                 id : item[0]
                           	, value: item[2]+'-'+item[1]
                               , label: item[2]+'-'+item[1]
                           }
                       }));
                   }
               });
        }
        , select: function( event, ui ) {
		    $("#industry\\.id").val(ui.item.id);
        }
    });
    //datepicker  
	$('[datepicker="datepicker"]').each(function(){
		var deliveryCycle = $(this).parent().children(":last-child").html().replace(/\r\n/g, "").trim();
		$(this).datepicker({
			  dateFormat: 'yy-mm-dd'
			, minDate: new Date(new Date().getTime() + deliveryCycle * 24 * 60 * 60 * 1000)
			, onClose: function(dateText, inst) {
				$('[name="'+$(this).attr('target') + '_year"]').val(inst.selectedYear)
				$('[name="'+$(this).attr('target') + '_month"]').val(inst.selectedMonth + 1)
				$('[name="'+$(this).attr('target') + '_day"]').val(inst.selectedDay)
			}
		}).attr("readonly", true)
    });
	//search product
	$("#searchProductNumber").autocomplete({
        source: function(request, response) {
            $.ajax({
                url: "${createLink(controller:'salesOrderAjax', action: 'productList')}",
                data: { term: request.term },
                dataType: "json",
                type: "POST",
                success: function( data ) {
                    response( $.map( data, function( item ) {return {
                        id : item[0]
                    	, value: $.trim(item[2])
                		, label: $.trim(item[2])+' | '+$.trim(item[1]) + ' | ' + $.trim(item[3]) + ' | ' + item[4]
            			, serialNumber : item[2]
        				, name : $.trim(item[1])
    					, standard : $.trim(item[3])
						, price : item[4]
						, category : 'NONE'
						, discount : 0.75
					}}));
                }
            });
        }
        ,select: function( event, ui ) {
			$("#searchProductId").val(ui.item.id);
			$("#searchProductNumber").val(ui.item.serialNumber)
			$("#searchProductName").html(ui.item.name);
			$("#searchProductStandard").html(ui.item.standard)
			$("#searchProductPrice").html(ui.item.price)
            //event.returnValue = false;
        }
    });
    $("#searchProductNumber").keypress(function(event){
        //判断是否是回车
        var code = event.keyCode||event.charCode
        if(code == 13){
            event.returnValue = false;
            addOrderDetail()
            return false;
        }else{
            event.returnValue = true;
            return true;
        }
    });

	$('input[name$="quantity"]').each(function(){
		$(this).keypress(myKeypress).focus(myFocus).blur(myBlur).bind('paste', myPaste).change(myChange)
	});
	$("a[delete=delete]").delegate("", "click", myDeleteRow);
	$(":submit[name=_action_update], :submit[name=create]").click(function(){
		var result = true
		$('[datepicker="datepicker"]').each(function(){
			if(!isDate($(this).val())){
				$(this).parent().addClass("errors")
				$(this).focus()
				result = false
			}
		})
        if(result == true){
            $.blockUI();
        }
		return result
	})
    initSearchProduct();
});
</script>
